package com.db4o.servlet;

import java.lang.ref.*;
import javax.servlet.http.*;

import com.db4o.*;

/**
 * db4o servlet source code.
 * <br><br>Use the methods in the @link{Db4oServlet} class.
 */
class ServletSession extends WeakReference
{
	private final static		String ATTRIBUTENAME = "Db4oSession";
	private ServletFile			i_file;
	private ObjectContainer		i_objectContainer;
	
	ServletSession(HttpSession a_session, ServletFile a_file){
		super(a_session);
		i_file = a_file;
		if(a_file.i_shareTransaction){
			i_objectContainer = a_file.i_objectContainer;
		}else{
			i_objectContainer = a_file.i_objectServer.openClient();
		}
		a_session.setAttribute(ATTRIBUTENAME + System.currentTimeMillis(), new ServletSessionTerminator(this));
	}
	
	protected void finalize () {
		terminate(true);
	}
	
	HttpSession getSession(){
		return (HttpSession)get();
	}
	
	void terminate(boolean callFile){
		try{
			if(i_file != null){
				if(! i_file.i_shareTransaction){
					i_objectContainer.close();
				}
				clear();
				if(callFile){
					i_file.sessionTerminated(this);
				}
				i_file = null;
			}
		}catch(Throwable t){
		}
	}
	
	ObjectContainer objectContainer() {
		return i_objectContainer;
	}
}

